package book.hadoop.ch04;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.util.ReflectionUtils;
/**
 * 参数：hdfs://hadoop.main:9000/sequence-file-test
 * @author conkeyn
 *
 */
public class SequenceFIleReaderDemo {

	public static void main(String[] args) throws IOException, URISyntaxException {
		String uri = args[0];
		Configuration config = new Configuration();
		FileSystem fs = FileSystem.get(new URI(uri), config);
		Path path = new Path(uri);
		SequenceFile.Reader reader = null;
		try {
			reader = new SequenceFile.Reader(fs, path, config);
			Writable key = (Writable) ReflectionUtils.newInstance(reader.getKeyClass(), config);
			Writable value = (Writable) ReflectionUtils.newInstance(reader.getValueClass(), config);
			long position = reader.getPosition();
			while (reader.next(key, value)) {
				String synSeen = reader.syncSeen() ? "*" : "";
				System.out.printf("[%s%s]\t%s\t%s\n", position, synSeen, key, value);
				position = reader.getPosition();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeStream(reader);
		}
	}

}
